package com.heatup.apt.management.filter;

import com.heatup.apt.common.util.StringUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

public class SessionFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {
        try {
            req.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession();
        String url = request.getServletPath();
        if (url.contains("system/pre") || url.contains("login.jsp")
                || url.contains(".css") || url.contains(".js") || url.contains(".png") || url.contains(".jpg")||url.contains("download_file")) {
            chain.doFilter(request, response);
        } else {
            if (session.getAttribute("sys_user") == null) {
                session.invalidate();
                loginOut(request, response);
            } else {
                Object menus = session.getAttribute("menus");

                String max_url = url;
                max_url = url.split("/")[1] + "/" + url.split("/")[2];
                //符合权限或者不做权限判断的代码
                if (StringUtil.isNotEmpty(menus) && !menus.toString().contains(max_url) &&
                        StringUtil.isNotEquals(url, "/system/to_index") &&
                        StringUtil.isNotEquals(url, "/system/user/to_change_password")
                        && StringUtil.isNotEquals(url, "/system/order/to_course_dispel")	
                        && StringUtil.isNotEquals(url, "/system/user/change_password")) {
                    noPermission(request, response);
                } else {
                    chain.doFilter(request, response);
                }
            }
        }
    }

    @Override
    public void destroy() {
    }

    /**
     * session失效跳转到登陆页面
     *
     * @param request
     * @param response
     */
    private void loginOut(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = null;
        try {
            String url = request.getRequestURI();
            if (StringUtils.isNotBlank(request.getQueryString())) {
                //添加查询参数否则带参数的跳转URL 可能会报异常
                url += "?"+request.getQueryString();
            }
            out = response.getWriter();
            out.println("<script language='javascript' type='text/javascript'>");
            out.println("alert('由于你长时间没有操作,导致Session失效!请你重新登录!');window.top.location.href='" + request.getContextPath() + "/system/pre/to_login?returnUrl="+url+"'");
            out.println("</script>");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();//此处流应该关闭 否则容易内存泄漏 blank
            } catch (Exception ex) {
            }
        }
    }


    private void noPermission(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.println("<script language='javascript' type='text/javascript'>");
            out.println("alert('您没有权限访问该资源!');");
            out.println("</script>");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();//此处流应该关闭 否则容易内存泄漏 blank
            } catch (Exception ex) {
            }
        }
    }

}
